<template>
  <div class="workshop-management-container">
    <common-layout>
      <template #header-buttons>
        <div class="card-header">
          <span>生产车间管理</span>
          <el-button type="primary" @click="handleAdd">新增车间</el-button>
        </div>
      </template>

      <template #search-form>
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="车间编码" :style="{width: '260px'}">
            <el-input v-model="searchForm.code" placeholder="请输入车间编码"></el-input>
          </el-form-item>
          <el-form-item label="车间名称" :style="{width: '260px'}">
            <el-input v-model="searchForm.name" placeholder="请输入车间名称"></el-input>
          </el-form-item>
          <el-form-item label="车间状态" :style="{width: '260px'}">
            <el-select v-model="searchForm.status" placeholder="请选择状态">
              <el-option label="全部" value="-1"></el-option>
              <el-option label="激活" value="1"></el-option>
              <el-option label="停用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <template #data-content>
        <el-table :data="workshopList" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="code" label="车间编码"></el-table-column>
          <el-table-column prop="name" label="车间名称"></el-table-column>
          <el-table-column prop="description" label="车间描述"></el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">{{ scope.row.status === '1' ? '激活' : '停用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
          <el-table-column prop="updatedAt" label="更新时间" width="180"></el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" :type="scope.row.status === '1' ? 'danger' : 'success'" @click="handleStatusChange(scope.row.id, scope.row.status === '1' ? '0' : '1')">{{ scope.row.status === '1' ? '停用' : '激活' }}</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </template>
    </common-layout>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="车间详情" width="70%">
      <el-descriptions :column="2" title="基本信息" border>
        <el-descriptions-item label="车间编码">{{ currentWorkshop?.code }}</el-descriptions-item>
        <el-descriptions-item label="车间名称">{{ currentWorkshop?.name }}</el-descriptions-item>
        <el-descriptions-item label="车间描述">{{ currentWorkshop?.description }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ currentWorkshop?.status === '1' ? '激活' : '停用' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentWorkshop?.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentWorkshop?.updatedAt }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑车间对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="车间编码" v-if="isEdit">
          <el-input v-model="formData.code" disabled></el-input>
        </el-form-item>
        <el-form-item label="车间名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入车间名称" />        
        </el-form-item>
        <el-form-item label="车间描述" prop="description">
          <el-input v-model="formData.description" type="textarea" placeholder="请输入车间描述" />        
        </el-form-item>
        <el-form-item label="车间状态" prop="status">
          <el-select v-model="formData.status">
            <el-option label="激活" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog v-model="confirmDeleteVisible" title="确认删除" width="300px">
      <p>确定要删除该车间吗？</p>
      <template #footer>
        <el-button @click="confirmDeleteVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as workshopApi from '@/api/workshop'
import CommonLayout from '../components/CommonLayout.vue'

// 车间列表数据
const workshopList = ref<any[]>([])
const loading = ref(false)

// 当前车间数据
const currentWorkshop = ref<any>(null)

// 对话框状态
const detailDialogVisible = ref(false)
const dialogVisible = ref(false)
const confirmDeleteVisible = ref(false)

// 编辑状态
const isEdit = ref(false)
const dialogTitle = ref('新增车间')

// 搜索表单
const searchForm = reactive<{ code: string; name: string; status: string }>({
  code: '',
  name: '',
  status: '-1'
})

// 分页数据
const pagination = reactive<{ currentPage: number; pageSize: number; total: number }>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive<{ id: number | null; code: string; name: string; description: string; status: string }>({
  id: null,
  code: '',
  name: '',
  description: '',
  status: '1'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入车间名称', trigger: 'blur' },
    { min: 2, max: 20, message: '车间名称长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '车间描述不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 表单引用
const formRef = ref<any>(null)

// 删除ID已不再使用，由currentWorkshop代替
// const deleteId = ref<number | null>(null)

// 获取车间列表
const getWorkshopList = async () => {
  loading.value = true
  try {
    const response = await workshopApi.getWorkshops()
    workshopList.value = response.data
    pagination.total = response.data.length
  } catch (error: any) {
    ElMessage.error('获取车间列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索操作
const handleSearch = () => {
  // 在实际应用中，这里应该根据搜索条件过滤数据
  getWorkshopList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = '-1'
  getWorkshopList()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getWorkshopList()
}

// 当前页码变化
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current
  getWorkshopList()
}

// 查看车间详情
const handleView = async (workshop: any) => {
  try {
    // 在实际应用中，这里应该调用API获取车间详情
    currentWorkshop.value = workshop;
    detailDialogVisible.value = true;
  } catch (error: any) {
    ElMessage.error('获取车间详情失败: ' + error.message);
  }
}

// 新增车间
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增车间'
  formData.id = null
  formData.name = ''
  formData.description = ''
  formData.status = '1'
  dialogVisible.value = true
}

// 编辑车间
const handleEdit = (row: any) => {
  isEdit.value = true
  dialogTitle.value = '编辑车间'
  formData.id = row.id
  formData.name = row.name
  formData.description = row.description
  formData.status = row.status.toString()
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    if (!isEdit.value) {
      // 新增
      await workshopApi.createWorkshop({
        name: formData.name,
        description: formData.description,
        status: parseInt(formData.status)
      })
      ElMessage.success('新增车间成功')
    } else {
      // 编辑
      await workshopApi.updateWorkshop(formData.id!, {
        id: formData.id,
        name: formData.name,
        description: formData.description,
        status: parseInt(formData.status)
      })
      ElMessage.success('编辑车间成功')
    }
    dialogVisible.value = false
    getWorkshopList()
  } catch (error: any) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

// 删除车间
const handleDelete = (workshop: any) => {
  currentWorkshop.value = workshop
  confirmDeleteVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    await workshopApi.deleteWorkshop(currentWorkshop.value.id)
    ElMessage.success('删除车间成功')
    confirmDeleteVisible.value = false
    getWorkshopList()
  } catch (error: any) {
    ElMessage.error('删除车间失败: ' + error.message)
  }
}

// 更改车间状态
const handleStatusChange = async (id: number, status: string) => {
  try {
    await workshopApi.changeWorkshopStatus(id, parseInt(status))
    ElMessage.success(`车间已${status === '1' ? '激活' : '停用'}`)
    getWorkshopList()
  } catch (error: any) {
    ElMessage.error('更改车间状态失败: ' + error.message)
  }
}

// 页面加载时获取车间列表
onMounted(() => {
  getWorkshopList()
})
</script>

<style scoped>
.workshop-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>